<template>
    <div class="switch-wrap" :class="{'is-checked': isChecked, 'is-loading': isLoading}" @click="switchChange">
        <span class="switch-handel">
            <i class="iconfont icon-loading is-loading-animation" v-if="isLoading"></i>
        </span>
    </div>
</template>
<script setup>
import { computed, ref } from "vue"
import { dataTypes } from "@/utils/index"
const props = defineProps({
    checkedValue: {
        type: [Boolean, String, Number],
        default: true
    },
    uncheckedValue: {
        type: [Boolean, String, Number],
        default: false
    },
    params: {
        type: Object,
        default: () => ({})
    },
    beforeChange: Function
})
//  emit
const emit = defineEmits(["change"])
//modelValue
const modelValue = defineModel() // true
// isLoading
const isLoading = ref(false)
/** 选中 */
const isChecked = computed(() => modelValue.value === props.checkedValue)

/** change */
const switchChange = () => {
    // 防止连续触发
    if(isLoading.value) {
        return
    }
    const isFunction = dataTypes().isFunction(props.beforeChange)
    if(!isFunction) {
        checkedValue()
        return
    }
    isLoading.value = true
    // 异步
    props.beforeChange(props.params).then(() => {
        checkedValue()
        isLoading.value = false
    }).catch(() => {
        isLoading.value = false
    })
}

/** checked value */
const checkedValue = () => {
    const value = isChecked.value ? props.uncheckedValue : props.checkedValue
    modelValue.value = value
    emit("change", value)
}

</script>
<style lang="scss" scoped>
.switch-wrap {
    position: relative;
    width: 48px;
    height: 28px;
    padding: 4px;
    border-radius: 100px;
    background-color: #E2E6F1;
    box-sizing: border-box;
    cursor: pointer;
    &.is-checked {
        background-color: #3069FF;
        .switch-handel {
            left: 50%;
        }
    }
    &.is-loading {
        opacity: 0.6
    }
}
.switch-handel {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    width: 20px;
    height: 20px;
    left: 0%;
    background-color: #fff;
    border-radius: 100px;
    transition: .3s;
}
</style>